package model.roomManagement.Implementation;



import java.io.File;
import java.io.IOException;


import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;

import java.util.ArrayList;
import java.util.Observable;

import java.util.Vector;

import controller.ServerController;




import view.ViewObserver;


import model.drawServer.Implement.DrawRoom;
import model.drawServer.Implement.DrawServer;
import model.drawServer.Interface.IDrawServer;
import model.fshare.server.ServerFileShareControl;
import model.fshare.server.ServerFileShareController;

import model.roomManagement.Interface.IDBC;
import model.roomManagement.Interface.IServer;
import model.roomManagement.Interface.IUser;
import model.roomManagement.Interface.ViewObservable;
import model.textchatserver.RoomTChatSocketsManager;
import model.textchatserver.TChatSocketDistributor;







public class Server extends UnicastRemoteObject  implements IServer,ViewObservable{
	
	
	
     
	 static IDBC db=new JDBCTest();

	 static int socketPort = 5566;//客户端连接端口号
	 static int remotePort = 1099;//远程调用端口号

	 
	 public static String serverIp=null;
	 
	


	static Vector<Client> clients = new Vector<Client>(100);//存储连接客户信息 
	 static ServerSocket server = null; //建立服务器socket 
	Socket socket = null; //套接字连接 
	 

	 
	 static ArrayList<Room> roomList=new ArrayList();
	 
	 
	 static IDrawServer ds;
	 AudioServer as;
	 ServerFileShareControl sfs;
	static ArrayList<ViewObserver> viewObservers=new ArrayList();
	
	public Server() throws RemoteException {
		
		
		
		super();	

		
		ServerController SC=new ServerController(this);

	 } 
	
	
	public void open() throws UnknownHostException,IOException {
	
			 serverIp=(InetAddress.getLocalHost()).getHostAddress() ;
	
	
		  
			 
			
				server  = new ServerSocket(socketPort);
			
			   
			   
			    	  LocateRegistry.createRegistry(remotePort);
			    	  //LocateRegistry.createRegistry(1010);
			    	 // IServer server=new Server();
			    	// Naming.rebind("Server",this);
			    	  String URL="//"+serverIp+":"+remotePort+"/Server";
			    	 
			    	 Naming.rebind(URL,this);
			
				    this.startDb();
		
				    
				    
				     	
			   //   as=new AudioServer(this);//new 语音
			      ds=new DrawServer();    //new Draw
			       ds.start();
			      sfs=new ServerFileShareController();
			      sfs.startService();
			      
			      TChatSocketDistributor.getInstance();
			      

				    Accept accept=new Accept();
				    accept.start();
				    

			   
	}

	class Accept extends Thread { 
		  public void run() {
			   while (true) { 
				    try {
						socket = server.accept();
					} catch (IOException e) {
						
						e.printStackTrace();
					} //等待连接 
	/////////////////////////
					
				    Client client = new Client(socket); //实例化一个客户线程(其中线程Client中有Socket，这
				//里的的Socket只是起个过度作用) 
				    // 
				    clients.add(client);//增加客户线程到向量中 
				    client.start();//启动线程 
				    
				    notifyViewObservers();
				    
				  //  notifyChatRoom(client.userRoomId); //监视聊天室连接变化 
				   } 
			  
		  }
		
	}
	
	

	public static RoomTChatSocketsManager getRoomTCSocketManager(int roomId){
		Room temp = null;
		for(int i=0;i<roomList.size();i++){
			temp=roomList.get(i);
			if(temp.getRoomId()==roomId){
				break;
			}
			temp=null;
		}
		if(temp==null){
			temp=new Room(roomId);
			roomList.add(temp);
			notifyViewObservers();
		}
		
		return temp.RTCSM;
	}
	public static void deleteRoom(int roomId){
		Room temp = null;
		for(int i=0;i<roomList.size();i++){
			temp=roomList.get(i);
			if(temp.getRoomId()==roomId){
		
					roomList.remove(temp);
					notifyViewObservers();

				break;
			}
		}
		
	
	}
	

	public static void notifyChatRoom(int userRoomId) { //监视客户端线程 
		notifyViewObservers();
	
		  StringBuffer updata = new StringBuffer("updata"); 
		   for (int i = 0; i < clients.size(); i++) { 
		   Client c = (Client)clients.elementAt(i); 
		   if(c.userRoomId==userRoomId){   //是否处于同一房间 
		  
			   updata.append(":"+c.audioInetSocketAddress.getAddress().getHostAddress()+"/"+c.audioInetSocketAddress.getPort()+"/"+c.userId+"/"+c.userName); //客户端姓名字符串 
		   }
		   } 
	
			  
		  sendClients(updata,userRoomId);//发送信息到客户端
		 
		
		 } 
	 public static void sendClients(StringBuffer message,int userRoomId) { 
		  for (int i= 0 ; i < clients.size(); i++) { 
		   Client client = (Client)clients.elementAt(i);//分别得到每个客户端的连接 
		   if(client.userRoomId==userRoomId)
		   client.send(message);//发送信息 
		  } 
		 } 
	 
	 public static  void notifyEnter(String ip,int roomId ){
		// ds.userEnterRoom(ip, roomId);
		 
	 }
	 public static void notifyLeave(String ip,int roomId ){
		// ds.userLeaveRoom(ip, roomId);
		 
	 }
	// roomid socket userid
	 
	 public static void disconnect(Client client) {// 断开客户端 
		  try { 
		   System.err.println(client.ip+"断开连接\n"); 
		  } catch (Exception ex) { 
		   ex.printStackTrace(); 
		  } 
		  clients.removeElement(client); 
		  client.socket = null; 
		 }

	 
			 

	@Override
	public int creatRoom(int userId,String subject,String password) throws RemoteException {
		
		
		
		return db.creatRoom(userId,subject,password);
	}

	@Override
	public boolean deletRoom(int userId, int roomId) throws RemoteException {
		
		return db.deleteRoom(userId,roomId);
	}

	@Override
	public ArrayList getRoomByUId(int userId) throws RemoteException {
		try {
			return db.getRLbyUserId(userId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	return null;
	}


	@Override
	public ArrayList getUserByRId(int roomId) throws RemoteException {
		try {
			return db.getULbyRoomId(roomId);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public int loginCheck(int userId, String password)
			throws RemoteException {
		boolean right=false;
		
		right=db.userCheck(userId, password);
		
		
		  for (int i = 0; i < clients.size(); i++) { 
			   Client c = (Client)clients.elementAt(i); 

			   if(c.userId==userId)   //或用户ID
			   return 2; //用户已经登录
			  } 
		
		
		// TODO Auto-generated method stub
		  if(right)
			  return 1; //登录成功
		return 0; //帐号密码错误
	}



	@Override
	public boolean userEnter(int userId, int roomId) throws RemoteException {
		ArrayList roomlist;
		try {
			roomlist = db.getRLbyUserId(userId);
			if(roomlist.contains(roomId))
				return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		return false;
	}


	@Override
	public boolean userJoin(int userId, int roomId,String password) throws RemoteException {
	
		if(!db.joinCheck(roomId,password))
			return false;
		
		if(db.addUtoR(roomId,userId)&&db.addRtoU(userId,roomId))
			return true;
	
		return false;
		
	}





	@Override
	public boolean userQuit(int userId, int roomId) throws RemoteException {
		 
		if(db.deleteUofR(roomId,userId)&&db.deleteRofU(userId,roomId))
			return true;
		
		return false;
	}

	
	public static void main(String[] argv)
	   {
	      try
	      {

	    	  IServer server=new Server();
	    		

	      }catch (Exception e)
	      {
		        e.printStackTrace();
		      }
	       

	         
	   }

	public void startDb() {
		db.start();


	}

	@Override
	public IUser getUserById(int id) {

		
		
		try {
			return db.getUserInfoByUId(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
		


	@Override
	public ArrayList<String> getCurrentInfoByRoomId(int roomId)
			throws RemoteException {
		ArrayList<String> infoList=new ArrayList<String> ();
		Client c=null;
		for(int i=0;i<clients.size();i++){
			c=clients.elementAt(i);
			if(c.userRoomId==roomId)
				infoList.add(c.ip+":"+c.userName+"/"+c.userId);
			
		}
		
		return infoList;
	}

	@Override
	public String getRoomInfoByRId(int roomId) throws RemoteException {
	
		try {
			return db.getRoomInfoByRId(roomId);
		} catch (Exception e) {
	
			e.printStackTrace();
			return null;
		}
	}


	public boolean addAudioAddress(int userId,InetSocketAddress AudioInetSocketAdress){
		for(int i=0;i<clients.size();i++){
			
			if(clients.get(i).userId==userId){
				clients.get(i).audioInetSocketAddress=AudioInetSocketAdress;
				return true;
			}
		}
		
		return false;
	}
	

	
	
	public static IDBC  getDB(){
		return db;
		
	}


	@Override
	public boolean changePassWord(int userId, String oldPassword,
			String newPassword) throws RemoteException {
		// TODO Auto-generated method stub
		return db.changePassWord(userId,oldPassword,newPassword);
	}


	@Override
	public void addViewObserver(ViewObserver viewObserver) {
		viewObservers.add(viewObserver);
		
	}



	public static void notifyViewObservers() {
		for(int i=0;i<viewObservers.size();i++){
			viewObservers.get(i).updata();

		}
		
	}

	public int getClientCount(){
		return clients.size();
	}
	public int getRoomCount(){
		return roomList.size();
	}



	public void close() throws IOException {
		
    System.exit(-1);

	}
}
